package com.cmos.um.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cmos.um.beans.CtiMessage;
import com.cmos.um.beans.CtiMessageExtends;
import com.cmos.um.iservice.ICtiMessageSV;
import com.cmos.um.iservice.IUploadSampleSV;
import com.cmos.um.utils.FileUtil;
import com.cmos.um.utils.RetMap;
import com.cmos.um.utils.WSContent;
import com.cmos.um.utils.WSRtnJsonCtx;
import com.cmos.um.utils.*;
import com.cmos.um.utils.http.RestClientHttpRequest;
import com.google.common.base.Joiner;
import netscape.javascript.JSObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
public class UploadSampleSVImpl implements IUploadSampleSV {

    @Autowired
    private ICtiMessageSV iCtiMessageSV;
    @Autowired
    private RestClientHttpRequest clien;

    private final static Logger logger = LoggerFactory.getLogger(UploadSampleSVImpl.class);

    /**
     * 【操作】样本上传通知接口（是任务管理平台向统一调度平台下传号码文件，再由统一调度平台传到media中导入sdp库中）
     *
     * @param params 参数集MAP（含params参数——此参数在输入函数时为Json字符串）
     * @return Map<String                                                                                                                               ,                                                                                                                               Object> 返回的数据（MAP形式）
     */
    @Override
    @Transactional
    public Map<String, Object> synchMessageforUploadsmaple(JSONObject params) {
        JSONObject toCC = new JSONObject();
        // 根據ftp地址和配置好的ftp（user,passwd）将文件下载到本地并读出其中的campaignId
        JSONObject P_params = params.getJSONObject("params");
        String urlStr = P_params.getString("uploadFileName");//要下载的文件路径
        String nowTime = (new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date());
        String localFileName = nowTime + ".txt"; //文件名为当前时间
        //下载文件
        try {
            FileUtil.downLoadFromUrl(urlStr, localFileName, WSContent.localPath);
            File localFile = new File(WSContent.localPath + localFileName);//下载到本地的文件
            String fileContent = FileUtil.txt2String(localFile);//读取出文件的内容
            if (fileContent == null || fileContent.isEmpty()) {
                logger.error("文件内容为空");
                return new RetMap(logger, "文件" + urlStr + localFileName + "内容为空");
            }
            String[] txt = fileContent.split(",");//拆分转化为数组
            String campaign_id = txt[1];// 通过下载的文件读出需要的任务id
            String serviceId = "000001" + WSContent.companyNo + "11" + campaign_id;//新方任务id
            //3.1 根据campaignId查找cti_message_task是要给那个cti提供FTP地址，并根据其中的cti_id查找cti_ip并通知
            CtiMessage cti = iCtiMessageSV.queryCtimessageBytaskId(campaign_id);//查找出需要的cti信息
            if (cti == null) {
                return new RetMap("0", "没有找到文件中任务号对应的cti");
            }
            String NumberServerIp = cti.getNumberServerIp();//要上传到的ctiip地址
            String cti_ip = cti.getCtiIp();// CTI服务器的IP地址
            String fileName = "Number_" + nowTime + campaign_id + ".txt";//要上传的文件名
            InputStream input = new FileInputStream(localFile);
            String uploadAddress = MessageFormat.format(WSContent.uploadUrl, NumberServerIp, fileName);//拼接成完整的要上传的文件路径
            FileUtil.uploadFile(uploadAddress, input, fileName);//上传到cti服务器
            toCC.put("servicetype", "3"); //
            toCC.put("serviceId", serviceId); //
            toCC.put("callNumberFile", "/media/" + WSContent.companyNo + "/outAddress/" + fileName); // 上传文件时路径格式6 位企业标识/outAddress/
            toCC.put("mediaFile", fileName); // 上传的文件名为字母或数字组成
            WSRtnJsonCtx result = clien.doPost(WSContent.servUrl, cti_ip, "addOutTaskNumberFile", "1", toCC);
            if (!"0".equals(result.getRescode())) {
                logger.error("调用cti接口失败，返回的信息为：" + result.getResJsonObj());
                return new RetMap("0", "调用cti接口失败，返回的信息为：" + result.getResJsonObj());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new RetMap("0", e.getMessage());
        }
        //5 函数正常结束，返回正常响应
        return new RetMap("成功");
    }


    /**
     * 样本删除通知接口
     */
    @Override
    public Result smapleDelete(JSONObject params) {
        JSONObject JsonParams = params.getJSONObject("params");
        //任务短号
        String serviceId = JsonParams.getString("campaignId");
        // 新方任务id
        String xfServiceId = "000001" + WSContent.companyNo + "11" + serviceId;
        //JSONArray transparentParams = JsonParams.getJSONArray("transparentParam");
        JSONArray transparentParams = params.getJSONArray("beans");

        //把参数transparentParam 做处理 加上引号 用于cti直接sql查询
        List string = new ArrayList();
        for (Object list : transparentParams) {
            JSONObject lists = (JSONObject) list;
            //样本id
            String sampleId =lists.getString("sampleId");
            sampleId= "'" + sampleId + "'";
            string.add(sampleId);
        }
        String transparentParam = Joiner.on(",").join(string);

        JSONObject sendParams = new JSONObject();
        sendParams.put("serviceId", xfServiceId);
        sendParams.put("transparentParam", transparentParam);

        CtiMessageExtends ctiInfo = iCtiMessageSV.queryCtimessageBytaskId(serviceId);
        String ctiIp = ctiInfo.getCtiIp();
        //1.先根据sercieId和transparentParam查出任务样本的状态
        WSRtnJsonCtx resultTask = clien.doPost(WSContent.servUrl, ctiIp, "findPhoneResult", WSContent._OTHER, sendParams);
        if (!"0".equals(resultTask.getRescode())) {
            logger.error("调用查询任务样本状态接口失败，返回的信息为：" + resultTask.getResJsonObj());
            return ResultUtil.error("0", "调用cti接口失败，返回的信息为：" + resultTask.getResJsonObj());
        }
        JSONArray taskInfos = resultTask.getContextArr();
        if (taskInfos==null){
            logger.error("调用查询任务样本状态接口失败，返回的信息为：" + resultTask.getResJsonObj());
            return ResultUtil.error("0", "调用查询任务样本状态接口失败，返回的信息为：" + resultTask.getResJsonObj());
        }

        sendParams.clear();
        sendParams.put("serviceId", serviceId);
        List phoneIds = new ArrayList();
        for (Object taskInfo : taskInfos) {
            JSONObject Jparams = (JSONObject) taskInfo;
            String state = Jparams.getString("state");
            if ("00".equals(state)) {
                phoneIds.add(Jparams.getString("phone1"));
            }
        }
        if (phoneIds.size() == 0) {
            return ResultUtil.error("0", "没有未处理状态的样本");
        }
        sendParams.put("phoneId", phoneIds);
        WSRtnJsonCtx result = clien.doPost(WSContent.servUrl, ctiIp, "delTaskPhone", WSContent._DELETE, sendParams);
        if (!"0".equals(resultTask.getRescode())) {
            logger.error("调用更改任务样本状态接口失败，返回的信息为：" + result.getResJsonObj());
            return ResultUtil.error("0", "调用cti接口失败，返回的信息为：" + result.getResJsonObj());
        }

        return ResultUtil.success("0", "成功");
    }
}
